<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 汪利东,2016-04-19 11:02
// +----------------------------------------------------------------------

namespace Delivery\Model;


use Think\Model\RelationModel;

class DeliveryMyModel extends RelationModel
{
    protected $tableName = 'order_delivery';

    protected $_link = [
        'delivery_man' => [
            'mapping_type' => self::HAS_ONE,
            'foreign_key'  => 'man_id',
            'mapping_key'  => 'man_id',
        ],

        'book' => [
            'mapping_type' => self::HAS_MANY,
            'class_name'   => 'view_order_has_book',
            'foreign_key'  => 'order_id',
            'mapping_key'  => 'order_id',
        ],

        'order' => [
            'mapping_type' => self::HAS_ONE,
            'class_name'   => 'order_book',
            'foreign_key'  => 'order_id',
            'mapping_key'  => 'order_id',
        ],
        'product' => [
            'mapping_type' => self::MANY_TO_MANY,
            'foreign_key'  => 'order_id',
            'mapping_key'  => 'order_id',
            'relation_table' => 'order_has_product'
        ],
    ];

    protected function _after_select(&$result, $options)
    {
        parent::_after_select($result, $options);

        if (!empty($options['link'])) {
            $this->getRelations($resultSet, $options['link']);
        }

        if ($resultSet) {
            foreach ($resultSet as &$result) {
                $this->_after_find($result, $options);
            }
        }

        foreach ($result as $k => $v) {
            $result[$k]['order']['address'] = json_decode($v['order']['address'], true);
        }
    }

    protected function _after_find(&$result, $options)
    {
        parent::_after_find($result, $options);

        if (!empty($options['link'])) {
            $this->getRelations($resultSet, $options['link']);
        }

        $result['order']['address'] = json_decode($result['order']['address'], true);

        $result['order']['user'] =
            M('user')->alias('a')
                ->join('left join card b on b.user_id=a.user_id')
                ->where(['a.user_id' => $result['order']['user_id']])
                ->find();
    }
}